package com.punch.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.constant.CommonConstant;
import com.punch.common.dto.user.user.RedisUserDTO;
import com.punch.common.dto.login.WXUserDTO;
import com.punch.common.model.LoginUser;
import com.punch.common.simple.redis.utils.RedisUtil;
import com.punch.user.mapper.SysGuardianMapper;
import com.punch.user.model.SysGuardian;
import com.punch.user.service.GuardianService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * GuardianServiceImpl-家长实现层
 *
 * @author wujj
 * @version 1.0.0
 * @since 2020/8/10 14:23
 */
@Service
public class GuardianServiceImpl extends ServiceImpl<SysGuardianMapper, SysGuardian> implements GuardianService {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据openId获取监护人信息
     *
     * @param openId openId
     */
    @Override
    public LoginUser getFeignGuardianByOpenId(String openId) {
        QueryWrapper<SysGuardian> queryWrapper = new QueryWrapper<>();
        //根据openId获取家长信息
        queryWrapper.lambda().eq(SysGuardian::getOpenId, openId);
        SysGuardian sysGuardian = getOne(queryWrapper);
        LoginUser loginUser = new LoginUser();
        if (sysGuardian == null) {
            loginUser.setUserId(0L);
        } else {
            loginUser.setUserId(sysGuardian.getId());
            //用户信息存放redis中
            StringBuilder sb = new StringBuilder();
            sb.append(CommonConstant.SECURITY_REDIS_USER_PREFIX).append("app:").append(sysGuardian.getId());
            RedisUserDTO redisUserDTO = new RedisUserDTO();
            redisUserDTO.setOpenId(openId);
            redisUserDTO.setUserId(sysGuardian.getId());
            redisUtil.setValue(sb.toString(), redisUserDTO, 28800L);
        }
        return loginUser;
    }

    /**
     * 进行注册,不存在则注册,存在则返回
     *
     * @param wxUserDTO 微信用户表单
     * @return LoginUser
     */
    @Override
    public void saveFeignGuardian(WXUserDTO wxUserDTO) {
        QueryWrapper<SysGuardian> queryWrapper = new QueryWrapper<>();
        //根据openId获取家长信息
        queryWrapper.lambda().eq(SysGuardian::getOpenId, wxUserDTO.getOpenId());
        SysGuardian sysGuardianEX = getOne(queryWrapper);
        //不存在则注册
        if (sysGuardianEX == null) {
            SysGuardian sysGuardian = new SysGuardian();
            BeanUtils.copyProperties(wxUserDTO, sysGuardian);
            save(sysGuardian);
        } else {
            SysGuardian sysGuardian = new SysGuardian();
            BeanUtils.copyProperties(wxUserDTO, sysGuardian);
            sysGuardian.setId(sysGuardianEX.getId());
            updateById(sysGuardian);
        }
    }
}
